import axios from 'axios'
import { ElMessage } from "element-plus";
import { TOKEN_KEY } from '@/enums/cachEnum';
import { getToken } from '@/utils/auth/auth';

// create an axios instance
const request = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API, // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 5000, // request timeout
})

// request interceptor
request.interceptors.request.use(
    config => {
        let token = getToken(TOKEN_KEY);
        if (token) {
            config.headers['X-Token'] = token;
        }
        // do something before request is sent
        return config
    },
    error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
request.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
    */
  
    /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
    response => {
      console.info(response);

      const res = response.data
      console.info(res);
      // if the custom code is not 20000, it is judged as an error.
      if (res.status !== "error") {
        ElMessage({
          message: res.info || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
        return Promise.reject(new Error(res.info || 'Error'))
      } else {
        return res
      }
    },
    error => {
      console.log('err' + error) // for debug
      ElMessage({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(error)
    }
  )
  

export default request;